package 力扣日常刷题.木23一月.第11天311;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 帅小伙
 * @date 2022/3/11
 * @description
 */
public class Demo38三数之和 {

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        ArrayList<List<Integer>> ans = new ArrayList<>();
        int n = nums.length;
        if(n < 3 || nums[0] > 0) return ans;

        for (int i = 0; i < n; i++) {
            int l = i + 1,r = n - 1;

            while(l < r) {
                int sum = nums[i] + nums[r]+ nums[l];
                if(sum > 0)r--;
                else if(sum < 0) l++;
                else{
                    ArrayList<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(nums[l]);
                    list.add(nums[r]);
                    ans.add(list);
                    while(l < r && nums[l] == nums[l+1]) l++;
                    while(l < r && nums[r] == nums[r - 1]) r--;
                    l++;
                    r--;
                }
            }

            while(i+1 < n && nums[i] == nums[i+1]){
                i++;
            }


        }
        return ans;
    }

}
